import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken, removeToken } from '@/util/token-utils'

const baseURL = '/qy'

// post 
export function postAction(url, parameter) {
  return axios({
      url: baseURL + url,
      method: 'post',
      data: parameter,
      headers: { 'Content-Type': 'application/json' }
  })
}
//自定义请求方式
export function httpAction(url, parameter, method) {
  return axios({
      url: baseURL + url,
      method: method,
      data: parameter
  })
}
//put
export function putAction(url, parameter) {
  return axios({
      headers: {
          'Content-Type': 'application/json'
      },
      url: baseURL + url,
      method: 'put',
      data: parameter
  })
}
//get
export function getAction(url, parameter) {
  return axios({
      url: baseURL + url,
      method: 'get',
      params: parameter,
  })
}
//delete
export function deleteAction(url, parameter) {
  return axios({
      url: baseURL + url,
      method: 'delete',
      params: parameter
  })
}

//同步get请求
export function getSyncAction (option) {
  var param = ''
  if (option.data != {} && option.data != null) {
    var keys = Object.keys(option.data)
    for (var k of keys) {
      param = param + k + '=' + option.data[k] + '&' 
    }
    param = '?' + param.substring(0,param.length-1)
  }
  
  var xhr = new XMLHttpRequest()
  xhr.open('get', option.url + param, false)
  xhr.onreadystatechange = function(){
    if(xhr.readyState == 4 && xhr.status == 200){
      var res = JSON.parse(xhr.responseText)
      option.success(res)
    }
  }
  xhr.send()
}


// request 拦截
axios.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['QianYuanToken'] = getToken()
    }
    return config
  },
  error => {
    console.log(error) 
    return Promise.reject(error)
  }
)

// response 拦截
axios.interceptors.response.use(
  response => {
    const res = response.data

    if (res.code !== 1) {
      Message({
        message: res.msg || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      if (res.code === 3) {
        // 非法访问
        removeToken()
        window.location.reload()
      }

      return Promise.reject(new Error(res.msg || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) 
    Message({
      message: error.msg,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)
